package com.epam.DAO.impl;

import java.util.List;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.TypedQuery;

import com.epam.DAO.RequestDAO;
import com.epam.entity.Client;
import com.epam.entity.Request;
import com.epam.entity.Status;
import com.epam.utils.Interceptor;

@Interceptors(Interceptor.class)
@Stateless
public class RequestDAOImpl extends GenericDAOImpl<Request> implements
		RequestDAO {

	public RequestDAOImpl() {
		super(Request.class);
	}

	@Override
	public List<Request> getRequests(int first, int size, Status... status) {
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT r FROM Request r WHERE r.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR r.status = ?" + i);
		}
		TypedQuery<Request> query = em.createQuery(queryString.toString(),
				Request.class);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Request> list = query.setMaxResults(size).setFirstResult(first)
				.getResultList();
		return list;
	}
	
	@Override
	public int getRequestsCount(Status... status) {
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT r FROM Request r WHERE r.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR r.status = ?" + i);
		}
		TypedQuery<Request> query = em.createQuery(queryString.toString(),
				Request.class);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Request> list = query.getResultList();
		return list.size();
	}

	@Override
	public List<Request> getUserRequests(Client client, int first, int size,
			Status... status) {
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT r FROM Request r "
						+ "WHERE r.client = :client AND r.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR r.status = ?" + i);
		}
		TypedQuery<Request> query = em.createQuery(queryString.toString(),
				Request.class);
		query.setParameter("client", client);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Request> list = query.setMaxResults(size).setFirstResult(first)
				.getResultList();
		return list;
	}

	@Override
	public int getUserRequestsCount(Client client, Status... status) {
		StringBuffer queryString = new StringBuffer(
				"SELECT DISTINCT r FROM Request r "
						+ "WHERE r.client = :client AND r.status = ?1");
		for (int i = 2; i <= status.length; i++) {
			queryString.append(" OR r.status = ?" + i);
		}
		TypedQuery<Request> query = em.createQuery(queryString.toString(),
				Request.class);
		query.setParameter("client", client);
		for (int i = 0; i < status.length; i++) {
			query.setParameter(i + 1, status[i]);
		}
		List<Request> list = query.getResultList();
		return list.size();
	}

}
